package com.kds.smarthome.job;

import com.kds.smarthome.entity.enums.JobStatus;
import com.kds.smarthome.mapper.FunctionMapper;
import com.kds.smarthome.service.system.ScheduleEnergyStatistics;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * @author 孔德嵩
 * 创建日期 2025/4/18
 */
@Component
@Slf4j
public class EnergyStatisticsJob implements Job {

    @Autowired
    private ScheduleEnergyStatistics energyStatistics;

    @PostConstruct
    public void init() {
        log.info("EnergyStatisticsJob初始化，energyStatistics: {}", energyStatistics);
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            if (energyStatistics == null) {
                log.error("energyStatistics未注入，请检查配置");
                throw new JobExecutionException("energyStatistics未注入");
            }

            // 获取任务参数
            JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
            String methodName = jobDataMap.getString("method");
            log.info("开始执行能耗统计任务 - 方法: {}", methodName);

            // 获取当前时间并根据统计类型截断
            DateTime now = new DateTime();
            DateTime end;
            DateTime start;

            switch (methodName) {
                case "hourStatistics":
                    end = now.hourOfDay().roundFloorCopy();
                    start = end.minusHours(1);
                    break;
                case "dayStatistics":
                    end = now.dayOfMonth().roundFloorCopy();
                    start = end.minusDays(1);
                    break;
                case "monthStatistics":
                    end = now.dayOfMonth().roundFloorCopy().withDayOfMonth(1);
                    start = end.minusMonths(1);
                    break;
                default:
                    throw new JobExecutionException("未知的统计方法: " + methodName);
            }


            // 通过反射调用对应的统计方法
            try {
                Method method = ScheduleEnergyStatistics.class.getMethod(methodName, Date.class, Date.class);
                method.invoke(energyStatistics, start.toDate(), end.toDate());

                // 更新任务状态为正常
            context.getJobDetail().getJobDataMap().put("status", JobStatus.NORMAL.getCode());
                log.info("能耗统计任务执行完成 - 方法: {}, 开始时间: {}, 结束时间: {}",
                        methodName, start, end);
            } catch (Exception e) {
                throw new JobExecutionException("执行统计方法失败: " + e.getMessage(), e);
            }

        } catch (Exception e) {
            // 发生异常时更新状态
            context.getJobDetail().getJobDataMap().put("status", JobStatus.ERROR.getCode());
            log.error("任务执行失败", e);
            throw new JobExecutionException(e);
        }
    }
}
